package relop;

import global.RID;
import heap.HeapFile;
import heap.HeapScan;

/**
 * Wrapper for heap file scan, the most basic access method. This "iterator"
 * version takes schema into consideration and generates real tuples.
 */
public class FileScan extends Iterator {
	
	HeapFile hf;
	HeapScan h_scan;
	RID last;
  /**
   * Constructs a file scan, given the schema and heap file.
   */
  public FileScan(Schema schema, HeapFile file) {
    //throw new UnsupportedOperationException("Not implemented");
	  this.schema = schema;
	  hf = file;
	  h_scan = hf.openScan();
	  last = new RID();
  }

  /**
   * Gives a one-line explaination of the iterator, repeats the call on any
   * child iterators, and increases the indent depth along the way.
   */
  public void explain(int depth) {
    //throw new UnsupportedOperationException("Not implemented");
		System.out.printf("For the heapScan, the heapFile now is %s", hf.toString());

  }

  /**
   * Restarts the iterator, i.e. as if it were just constructed.
   */
  public void restart() {
    //throw new UnsupportedOperationException("Not implemented");
	  if(h_scan!=null)
		  h_scan = hf.openScan();
  }

  /**
   * Returns true if the iterator is open; false otherwise.
   */
  public boolean isOpen() {
    //throw new UnsupportedOperationException("Not implemented");
	  if(h_scan!=null) 
		  return true;
	  else
		  return false;
  }

  /**
   * Closes the iterator, releasing any resources (i.e. pinned pages).
   */
  public void close() {
    //throw new UnsupportedOperationException("Not implemented");
	  if(h_scan!=null)
		  h_scan.close();
  }

  /**
   * Returns true if there are more tuples, false otherwise.
   */
  public boolean hasNext() {
    //throw new UnsupportedOperationException("Not implemented");
	  if(h_scan!=null)
		  if(h_scan.hasNext())
			  return true;
		  else 
			  return false;
	  else 
		  return false;
  }

  /**
   * Gets the next tuple in the iteration.
   * 
   * @throws IllegalStateException if no more tuples 
   */
  public Tuple getNext() {
    //throw new UnsupportedOperationException("Not implemented");
	  if(h_scan!=null){
		  byte data[] = h_scan.getNext(getLastRID());
		  Tuple newtuple = new Tuple(this.schema, data);
		  return newtuple;
	  }
	  else
		  return null;
  }

  /**
   * Gets the RID of the last tuple returned.
   */
  public RID getLastRID() {
    //throw new UnsupportedOperationException("Not implemented");
	  RID lastone = this.last;
	  return lastone;
  }

} // public class FileScan extends Iterator
